/**
 * Created by vijanny on 2017-03-03.
 */

var net = require('net');
//var mb = require("./modbus");
var crc16 = require('./crc16');

var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
var HOST = '120.76.200.163';
//var HOST = '192.168.1.123';
var PORT = 3301;

var sockArr = [];
var count = 0;
var wifiSock = undefined;
var IHControllerSocket = undefined;
var RHootControllerSocket = undefined;
var RHootStatus=undefined;

var phpServiceSock = undefined;
var wifiAddress = '10.10.100.254';
var phpServiceAddress = '192.168.1.113';
var wifiLastData = undefined;
var callBackFun;
//var client = new mb();
//client.connectTcpRTUBuffered("192.168.1.221", { port: 8080 });
//client.setID(1);
//client.setTimeout(1000);




// 创建一个TCP服务器实例，调用listen函数开始监听指定端口
// 传入net.createServer()的回调函数将作为”connection“事件的处理函数
// 在每一个“connection”事件中，该回调函数接收到的socket对象是唯一的
console.log('auto  bulid and run  ');
var  getIPAdress = function(){
    var interfaces = require('os').networkInterfaces();
    for(var devName in interfaces){
        var iface = interfaces[devName];
        for(var i=0;i<iface.length;i++){
            var alias = iface[i];
            if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                console.log('auto  listen '+alias.address+':'+PORT);
                return alias.address;
            }
        }
    }
};




exports.Bytes2Str = function (arr) {
    var str = "";
    for (var i = 0; i < arr.length; i++) {
        var tmp = arr[i].toString(16);

        if (tmp.length == 1) {

            tmp = "0" + tmp;

        }

        str += tmp;

    }
    return str;
};

var localBytes2Str = function(arr){
    var str = "";
    for (var i = 0; i < arr.length; i++) {
        var tmp = arr[i].toString(16);

        if (tmp.length == 1) {

            tmp = "0" + tmp;

        }

        str +=' '+ tmp;

    }
    return str;
};

var bufTest = [0x55,0xAA,0xC8,0x00,0x00,0x00,0x00,0x00];
net.createServer(function (sock) {

    // 我们获得一个连接 - 该连接自动关联一个socket对象

    console.log('3301 wifi connected !!!' +
        sock.remoteAddress + ' ' + sock.remotePort);
    //wifiSock = sock;
    RHootControllerSocket = sock;
    sock.on('close', function (data) {
        //wifiSock = null;
        RHootControllerSocket = null;
        console.log('CLOSED: ' +
            sock.remoteAddress + ' ' + sock.remotePort);
    });
    //
    sock.on('error', function (data) {
        console.log('error: data ' + data + '\r\n' + 'from :' +
            sock.remoteAddress + ' ' + sock.remotePort);
            //wifiSock = null;
        RHootControllerSocket = null;
    });
    sock.on('data', function (data) {
        //if(callBackFun){
        //    callBackFun(data);
        //}
        console.log('RHood data:'+localBytes2Str(data));
        RHootStatus = data.slice(-8,-2);
        console.log('PORT 3301 :'+localBytes2Str(data.slice(-8,-2)));
    });


}).listen(PORT, getIPAdress());

var RHootReadStatus = new Buffer([0xAA,0x55]);
//setInterval(function(){
//    if(RHootControllerSocket){
//        RHootControllerSocket.write(RHootReadStatus);
//    }
//},1000);


net.createServer(function (sock) {

    // 我们获得一个连接 - 该连接自动关联一个socket对象

    console.log('3001 wifi connected !!!' +
        sock.remoteAddress + ' ' + sock.remotePort);
    IHControllerSocket = sock;
    sock.on('close', function (data) {
        //wifiSock = null;
        IHControllerSocket = null;
        console.log('CLOSED: ' +
            sock.remoteAddress + ' ' + sock.remotePort);
    });
    //
    sock.on('error', function (data) {
        console.log('error: data ' + data + '\r\n' + 'from :' +
            sock.remoteAddress + ' ' + sock.remotePort);
        //wifiSock = null;
        IHControllerSocket = null;
    });
    sock.on('data', function (data) {
        //if(callBackFun){
        //    callBackFun(data);
        //}
        var int16Buf = new Uint16Array(1);
        int16Buf[0] = crc16(bufTest);

        var U8input = new Uint8Array(int16Buf.buffer);
        console.log('bufTest = '+localBytes2Str(bufTest)+" crc16 = "+localBytes2Str(U8input));
    });


}).listen(3001, getIPAdress());


var buf = [0x33, 0x35, 0x36];




var mbTcp ={
    plcStatReg:(0x1000+150),
    plcDataReg:(0x1000+151),
    stateAddress:1,
    online:false,
    ready:false,
    curOrderIndex:0,
    orderBuff:[],
    initStart:false
};

var completeOrderList=[];

var errorCount = 0;
//setInterval(function(){
//
//    if(wifiSock){
//        wifiSock.setOnDataFun =setOnDataFun1;
//        client.setPort(wifiSock);
//        client.writeFC3(1,mbTcp.plcStatReg,1,function(error, data){
//            if(error){
//                mbTcp.online = false;
//                mbTcp.ready = false;
//                console.log(error);
//            }else{
//
//                mbTcp.online = true;
//                mbTcp.ready = false;
//                if(data.data==0x5555)  {
//                    //console.log(data);
//                    //若返回0x5555表明设备空闲
//                    mbTcp.ready = true;
//                    if(mbTcp.orderBuff.length>0){
//                        var value =0;
//                        console.log(mbTcp.orderBuff);
//                        if(mbTcp.initStart === true){
//                            value =0;
//                            for(var i = 0;i<mbTcp.orderBuff[0].orderList.length;i++){
//                                if(mbTcp.orderBuff[0].orderList[i]>0)
//                                    value += (1<<(mbTcp.orderBuff[0].orderList[i]-1));
//                            }
//                            client.writeFC6(mbTcp.stateAddress,mbTcp.plcDataReg,value,function(err,data){
//                                if(err){
//                                    errorCount++;
//                                    console.log(err);
//                                }else{
//                                    console.log('write fc 6 OK');
//                                    mbTcp.initStart=false;
//                                }
//                            })
//                        }else{
//                            //orderBuff中还存在ORDER即视为当前还未完成订单,当设备再次空闲时表明该订单已完成
//                            //向微信服务器端发送完成指令
//                            completeOrderList.push(mbTcp.orderBuff[0]);
//                            mbTcp.orderBuff.splice(0,1);
//                            //启动下一个订单配送
//                            if(mbTcp.orderBuff.length>0){
//                                value =0;
//                                for(var j = 0;j<mbTcp.orderBuff[0].orderList.length;j++){
//                                    if(mbTcp.orderBuff[0].orderList[j]>0)
//                                        value += (1<<(mbTcp.orderBuff[0].orderList[j]-1));
//                                }
//                                client.writeFC6(mbTcp.stateAddress,mbTcp.plcDataReg,value,function(err,data){
//                                    if(err){
//                                        errorCount++;
//                                        if(errorCount>10) wifiSock.close();
//                                        console.log(err);
//                                        mbTcp.ready = false;
//                                        mbTcp.online =false;
//                                    }
//                                });
//                            }
//
//                        }
//                    }
//
//                }
//                if(data.data==0xAAAA)  mbTcp.ready = false;
//                console.log('ready: '+mbTcp.ready);
//            }
//        });
//    }
//    else{
//        mbTcp.online = false;
//        mbTcp.ready = false;
//        console.log('wifi sock is null');
//    }
//},1200);
//
//setInterval(function(){
//    //return ;
//    if(completeOrderList.length>0){
//        var opts = {
//            url:'http://'+HOST+'/xnshop/page/index/plc.html',
//            method: 'POST',
//            json: true,
//            body: {
//                "plcHanderOrderInfo":[{
//                    "orderNumber":completeOrderList[0].orderNumber,
//                    "orderState":0
//                }]
//            }
//        };
//        request(opts).then(function (err, res, body) {
//            if (err.statusCode < 400) {
//                completeOrderList.splice(0,1);
//                console.log('POST host OK');
//            } else {
//                console.log('POST host err:');
//                console.log(err);
//            }
//        });
//    }
//},1500);



exports.sendData = function(order){
    //if(mbTcp.orderBuff.length==0){
    //    mbTcp.initStart = true;
    //}
    //mbTcp.orderBuff.push(order);
};
var setOnDataFun1 = function(cl){
    callBackFun=cl;
};
exports.setOnDataFun =function(cl){
    callBackFun=cl;
};

exports.getDevStatus = function(){
  //return {
  //    online:mbTcp.online,
  //    list:mbTcp.orderBuff
  //}
};

exports.resetOrder = function(){
    //mbTcp.orderBuff =[];
};

exports.sendDataIH = function(buf){
    if(IHControllerSocket){
       IHControllerSocket.write(buf);
    }
};
RHootStatus = [0x00,0x00,0x00,0x00,0x00,0x00];
exports.sendDataRH = function(k,v){
    if(RHootControllerSocket) {
        console.log('RHootStatus :'+localBytes2Str(RHootStatus));
        var setRH = [0x55,0xAA];
        for(var i = 0;i<RHootStatus.length;i++){
            setRH.push(RHootStatus[i]);
        }
        console.log('setRH bf :'+localBytes2Str(setRH));
        switch (k){
            case 'K1':
                if(v == true){
                    setRH[2]=0xC8;
                }else{
                    setRH[2]=0x00;
                }
                break;
            case 'K2':
                if(v == true){
                    setRH[3]=0xC8;
                }else{
                    setRH[3]=0x00;
                }
                break;
            case 'K3':
                if(v == true){
                    setRH[4]=0xC8;
                }else{
                    setRH[4]=0x00;
                }
                break;
            case 'K4':
                if(v == true){
                    setRH[5]=0xC8;
                }else{
                    setRH[5]=0x00;
                }
                break;
        }
        //console.log('setRH af :'+localBytes2Str(setRH));
        if((k == 'K1'&&v == false)||(setRH[2]==0x00)){
            var lightOn= setRH[3];
            RHootStatus = [0x00,0x00,0x00,0x00,0x00,0x00];
            setRH= [0x55,0xAA,0x00,0x00,0x00,0x00,0x00,0x00];
            RHootStatus[1]=lightOn;
            setRH[3]=lightOn;
        }else{
            RHootStatus = setRH.slice(2,8);
        }

        var int16Buf = new Uint16Array(1);
        int16Buf[0] = crc16(setRH);

        var U8input = new Uint8Array(int16Buf.buffer);
        setRH.push(U8input[0]);
        setRH.push(U8input[1]);
        var data = new Buffer(setRH);
        console.log('sendRH data :'+localBytes2Str(data));
        RHootControllerSocket.write(data);
    }
};

exports.getRHStatus = function(){
    if(RHootControllerSocket) {

    }
};


